260. Single Number III

1. Question

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

2. Examples

Example 1:

Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation:  [5, 3] is also a valid answer.

Example 2:

Input: nums = [-1,0]
Output: [-1,0]

Example 3:

Input: nums = [0,1]
Output: [1,0]

3. Constraints

  • 2 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each integer in nums will appear twice, only two integers will appear once.

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/single-number-iii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

5.1. 双指针法

class Solution {
  public int[] singleNumber(int[] nums) {
    Arrays.sort(nums);
    int left = 0;
    int right = 0;
    int[] ans = new int[2];
    int index = 0;

    while (left < nums.length) {

      while (right < nums.length - 1 && nums[left] == nums[right + 1]) {
        right++;
      }

      if (left == right) {
        ans[index++] = nums[left];
        if (index == 2) {
          return ans;
        }
      }

      left = right + 1;
    }
    return ans;
  }
}

5.2. 哈希表法

class Solution {
  public int[] singleNumber(int[] nums) {
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i : nums) {
      map.put(i, map.getOrDefault(i, 0) + 1);
    }

    int[] ans = new int[2];
    int index = 0;

    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      if (entry.getValue() == 1) {
        ans[index++] = entry.getKey();
        if (index == 2) {
          return ans;
        }
      }
    }
    return ans;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""